package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.ViewDlPurOutBillIdSendCmd;
import com.jackrain.nea.fc.dl.mapper.ViewDLTPurOutBillIdMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.HashMap;

/**
 * 供应商发货单发出
 *
 * @author kangcong
 * @date 2018/08/15
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class ViewDlPurOutBillIdSendCmdImpl extends CommandAdapter implements ViewDlPurOutBillIdSendCmd {

    @Autowired
    QueryCpUtil queryCpUtil;

//    @Autowired
//    private PurOutBillIdPushEsService purOutBillIdPushEsService;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
//        log.debug("------------ViewDlPurOutBillIdSendCmdImpl==" + map.get("param").toString());
        log.info("ViewDlPurOutBillIdSendCmdImpl--map-->{}",map);

        ValueHolder vh = new ValueHolder();
        ViewDLTPurOutBillIdMapper viewDLTPurOutBillIdMapper = ApplicationContextHandle.getBean(ViewDLTPurOutBillIdMapper.class);

        JSONObject param = null;
        try {
            param = JSON.parseObject(map.get("param").toString());
        } catch (Exception e) {
            vh.put("CODE", "-1");
            vh.put("MSG", "请求参数转json错误，" + map.get("param").toString());
            e.printStackTrace();
            return vh;
        }

        if (param == null || param.size() == 0) {
            vh.put("CODE", "-1");
            vh.put("MSG", "参数转json后为空，param=" + map.toString());
            return vh;
        }
//        log.debug("------------jsonobject==" + param.toString());

        String billNo = param.getString("OUT_BILL_NO");
        String storeEcode = param.getString("CP_C_STORE_ECODE");
        String supplierEcode = param.getString("CP_C_SUPPLIER_ECODE");

        boolean flag1 = billNo == null || storeEcode == null || supplierEcode == null || param.getString("OWNERNAME") == null || param.getString("OUT_BILL_DATE") == null;
        if (flag1) {
            vh.put("CODE", "-1");
            vh.put("MSG", "请求参数不正确==" + param.toString());
            return vh;
        }

        JSONObject whereJs1 = new JSONObject();
        whereJs1.put("ECODE", storeEcode);
        JSONObject h1 = queryCpUtil.queryCP("CP_C_STORE", "ID, ENAME", whereJs1);

        JSONObject whereJs2 = new JSONObject();
        whereJs2.put("ECODE", supplierEcode);
        JSONObject h2 = queryCpUtil.queryCP("CP_C_SUPPLIER", "ID, ENAME", whereJs2);

//        log.debug("CP_C_STORE请求数据：" + h1.toJSONString());
//        log.debug("CP_C_SUPPLIER请求数据：" + h2.toJSONString());

        boolean flag = h1 == null || h2 == null || h1.size() == 0 || h2.size() == 0;
        if (flag) {
            vh.put("CODE", "-1");
            vh.put("MSG", "关联CP_C_STORE 关联CP_C_SUPPLIER ，请求数据异常,请检查CP_C_STORE_ECODE CP_C_SUPPLIER_ECODE是否正确");
            return vh;
        }

        JSONObject insertKeys = new JSONObject();
        insertKeys.put("OUT_BILL_NO", billNo);
        insertKeys.put("OUT_BILL_DATE", param.getString("OUT_BILL_DATE"));
        insertKeys.put("CP_C_STORE_ID", h1.getLong("ID"));
        insertKeys.put("CP_C_STORE_ECODE", storeEcode);
        insertKeys.put("CP_C_STORE_ENAME", h1.getString("ENAME"));
        insertKeys.put("CP_C_SUPPLIER_ID", h2.getLong("ID"));
        insertKeys.put("CP_C_SUPPLIER_ECODE", supplierEcode);
        insertKeys.put("CP_C_SUPPLIER_ENAME", h2.getString("ENAME"));
        insertKeys.put("ISACTIVE", "Y");
        insertKeys.put("OWNERNAME", param.getString("OWNERNAME"));
        insertKeys.put("CREATIONDATE", new Timestamp(System.currentTimeMillis()).toString());
        insertKeys.put("MODIFIERNAME", param.getString("OWNERNAME"));
        insertKeys.put("MODIFIEDDATE", new Timestamp(System.currentTimeMillis()).toString());
        insertKeys.put("AD_CLIENT_ID", 37);
        insertKeys.put("AD_ORG_ID", 27);

        int count = viewDLTPurOutBillIdMapper.selectBillIdCount(billNo);

        try {
            int row = 0;
            if (count == 0) {
                //如果单子不存在，直接保存
                row = viewDLTPurOutBillIdMapper.insert("DL_T_PUR_OUT_BILL_ID", insertKeys);
            } else {
                //如果已存在，先删除在保存
                viewDLTPurOutBillIdMapper.deleteFromBillId(billNo);
                row = viewDLTPurOutBillIdMapper.insert("DL_T_PUR_OUT_BILL_ID", insertKeys);
            }
            if (row != 0) {
//                //通过单号查询数据，推ES
//                HashMap data = viewDLTPurOutBillIdMapper.selectDataByOutBillNo(billNo);
//                JSONObject esdata = new JSONObject(data);
//                purOutBillIdPushEsService.push(esdata, esdata.getLong("ID"));

                vh.put("CODE", "1");
                vh.put("MSG", "success");
            } else {
                throw new NDSException("更新数据库影响条数为0");
            }

        } catch (Exception e) {
            vh.put("CODE", "-1");
            vh.put("MSG", "操作数据库失败");

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            if ((e instanceof NDSException)) {
                throw e;
            } else {
                throw new NDSException(sw.toString());
            }
        }

        return vh;
    }
}
